<?php
class CategoryController extends Controller{
	
	public function filters(){
		return array(
				'accessControl'
		);
	}
	
	public function accessRules(){
		return array(
				array(
						'allow',
						'actions'=>array('list','add','edit','delete'),
						'users'=>array('@')
				),
				array(
						'deny',
						'users'=>array('*')
				)
		);
	}

	public function actionList(){
		$categoryModel = Category::model();
		$cateList = $categoryModel->cateTree(false);
		$this->render('list', array('cateList'=>$cateList));
	}

	public function actionAdd(){
		$categoryModel = new Category();
		if(isset($_POST['Category'])){
			//往模型层压入值
			$categoryModel->attributes = $_POST['Category'];
			if($categoryModel->validate()){
				if($res = $categoryModel->save()){
					$this->redirect(array('list'));
				}
			}
		}
		$categoryModel->sort = 1;
		$cateTree = $categoryModel->cateTree();
		$this->render('add', array('categoryModel'=>$categoryModel, 'cateTree'=>$cateTree));
	}
	
	/**
	 * 栏目ID号
	 * @param int $cid 栏目ID号
	 */
	public function actionEdit($cid){
		$categoryModel = Category::model()->findByPk($cid);
		$cateTree = $categoryModel->cateTree();
		if(isset($_POST['Category'])){
			$categoryModel->attributes = $_POST['Category'];
			if($categoryModel->save()){
				$this->redirect(array('list'));
			}
		}
		$this->render('add', array('categoryModel'=>$categoryModel, 'cateTree'=>$cateTree));
	}
	
	/**
	 * 删除
	 * @param int $cid 栏目ID号
	 */
	public function actionDelete($cid){
		$model = Category::model();
		
		//统计是否存在子栏目
		$count = $model->count('pid = :category_id', array(':category_id'=>$cid));
		
		//确定该栏目下是否存在文章
		$articleCount = Article::model()->count('category_id = :cid', array(':cid'=>$cid));
		
		if($count > 0 || $articleCount){
			$info = array(
					'status'=>0,
					'message'=>'删除失败，该栏目下存在子栏目或文章，请先删除'
			);
			echo json_encode($info);
			exit();
		}

		$res = $model->deleteByPk($cid);
		if($res){
			echo json_encode(array('status'=>1));
		} else {
			echo json_encode(array('stauts'=>0, 'message'=>'删除失败'));
		}
		exit();
	}
}